package controller;

import java.lang.String;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import dao.ADao;
import model.Users;
import model.q;
import model.a;

public class AController extends HttpServlet {

    public AController(){
        super();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        ADao adao = new ADao();
        String answers = request.getParameter("context");
        q q = (q)request.getSession().getAttribute("q");
        Users user = (Users)request.getSession().getAttribute("users");
        if(user == null){
            request.setAttribute("error","please login");
            request.setAttribute("idqa",q.getIdQA());
            request.getRequestDispatcher("/wenda.jsp").forward(request,response);
        }
        else if(answers==null){
            request.setAttribute("error","please input your answer");
            request.setAttribute("idqa",q.getIdQA());
            request.getRequestDispatcher("/wenda.jsp").forward(request,response);
        }
        else {
            a a = new a(q.getIdQA(),answers,user.getIdusers());
            try{
                int i = adao.save(a);
                if(i!=0){
                    request.setAttribute("idqa",q.getIdQA());
                    request.getRequestDispatcher("/wenda.jsp").forward(request,response);
                }
                else{
                    request.setAttribute("error","failed");
                    request.setAttribute("idqa",q.getIdQA());
                    request.getRequestDispatcher("/wenda.jsp").forward(request,response);
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
            out.flush();
            out.close();
        }

    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
